﻿using Esosi.Entity;
using Esosi.Register.Base.Dtos;
using Esosi.Repository.Models;
using Esosi.Repository.Tools;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Transactions;

namespace Esosi.Repository
{
    public class RegisterBalanceRespository : IRegisterBalanceRespository
    {
        private readonly HisContext _context;

        public RegisterBalanceRespository(HisContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public RegisterBalanceTpoDto SaveCtRegisterInfo(Guid guid)
        {
            try
            {
                var JsonInfo = _context.CtJsonRegisterInfos.FirstOrDefault(p => p.JsonGuidId == guid);

                var Models = CommonTools.DeserializeJsonToObject<RegisterBalanceJsonModel>(JsonInfo.StrJsonInfo);
                //var Models = CommonTools.getObjectByJson(JsonInfo.StrJsonInfo, registerBalanceJsonModel);
                using (TransactionScope transaction = new TransactionScope())
                {
                    _context.CtInvices.Add(Models.CtInvice);
                    //。。。。
                    foreach (var item in Models.Ctfee)
                    {
                        _context.CtFees.Add(item);
                    }
                    _context.SaveChanges();
                    transaction.Complete();
                }

                RegisterBalanceTpoDto registerBalanceTpoDto = new RegisterBalanceTpoDto()
                {
                    SaveResult = true,
                    Ctfee = Models.Ctfee,
                    CtInvice = Models.CtInvice,
                    CtInviceDetail = Models.CtInviceDetail,
                    CtRegisterInfo = Models.CtRegisterInfo
                };

                return registerBalanceTpoDto;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}